package unit;
import model.User;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class UserDao {
    public User getByName(String name) throws Exception{
        User user = null;
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/petclinic?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8", "root", "123456");
            ps = con.prepareStatement("select *from t_user as u where u.name=?");
            ps.setString(1, name);
            rs = ps.executeQuery();
            if (rs.next()) {
                user = new User();
                user.setId(rs.getInt("id"));
                user.setRole(rs.getString("role"));
                user.setName(rs.getString("name"));
                user.setPwd(rs.getString("pwd"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("数据库访问异常：" + e);
        }finally {
            if (rs !=null)
                rs.close();
            if (ps !=null)
                rs.close();
            if (con !=null)
                rs.close();
        }
        return user;
    }
}

